import { readFileSync, existsSync, statSync } from "fs";
import { defineEventHandler, setHeader } from "h3";
import { join, extname } from "path";

export default defineEventHandler(async (event) => {
  const filename = getRouterParam(event, 'filename');
  
  if (!filename) {
    throw createError({
      statusCode: 400,
      statusMessage: "Filename is required",
    });
  }

  // Decode URL-encoded filename
  const decodedFilename = decodeURIComponent(filename);
  
  const shareDir = "share-lan";
  const filePath = join(shareDir, decodedFilename);

  if (!existsSync(filePath)) {
    throw createError({
      statusCode: 404,
      statusMessage: "File not found",
    });
  }

  // Get file stats
  const stats = statSync(filePath);
  
  // Set appropriate headers for download
  const ext = extname(decodedFilename).toLowerCase();
  const mimeTypes: Record<string, string> = {
    '.pdf': 'application/pdf',
    '.txt': 'text/plain',
    '.json': 'application/json',
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg',
    '.png': 'image/png',
    '.gif': 'image/gif',
    '.mp4': 'video/mp4',
    '.mp3': 'audio/mpeg',
    '.zip': 'application/zip',
    '.doc': 'application/msword',
    '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  };

  const mimeType = mimeTypes[ext] || 'application/octet-stream';

  console.log(decodedFilename)
  
  setHeader(event, 'Content-Type', mimeType);
  setHeader(event, 'Content-Length', stats.size);
  setHeader(event, 'Content-Disposition', `attachment; filename="${filename}"`);

  console.log(decodedFilename)

  // Read and return file content
  return readFileSync(filePath);
}); 